package com.dn.luckbi.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.dn.luckbi.common.ErrorCode;
import com.dn.luckbi.exception.BusinessException;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * excel工具类
 *
 * @author 染染熊
 * @version 1.0
 * @date 2024/3/25 18:10
 */
public class ExcelUtils {

    /**
     * excel 转 csv
     * @return
     */
    public static String excelToCsv(MultipartFile multipartFile) {
        if (multipartFile == null || multipartFile.isEmpty()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件不能为空");
        }
        InputStream inputStream = null;
        try {
            inputStream = multipartFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        // 读取文件
        List<Map<Integer, String>> list = EasyExcel.read(inputStream)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet()
                .headRowNumber(0)
                .doReadSync();
        if (CollUtil.isEmpty(list)) {
            return "";
        }
        // 创建返回对象
        StringBuilder stringBuilder = new StringBuilder();
        // 获取表头
        Map<Integer, String> headerMap = list.get(0);
        List<String> headerList = headerMap.values().stream().filter(StrUtil::isNotBlank).collect(Collectors.toList());
        stringBuilder.append(StrUtil.join(",", headerList)).append("\n");
        // 获取内容
        for (int i = 1; i < list.size(); i++) {
            Map<Integer, String> dataMap = list.get(i);
            List<String> dataList = dataMap.values().stream().filter(StrUtil::isNotBlank).collect(Collectors.toList());
            stringBuilder.append(StrUtil.join(",", dataList)).append("\n");
        }
        System.out.println(stringBuilder);
        return stringBuilder.toString();
    }

    public static void main(String[] args) {
        excelToCsv(null);
    }


}
